//
//  WebOfflineURLProtocol.swift
//  ToBeBigFE
//
//  Created by mingo on 2020/3/5.
//  Copyright © 2020 com.example. All rights reserved.
//

import Foundation

class WebOfflineURLProtocol: URLProtocol {
    
    private static var urlProtocolEnabled = false
    
    class func enableURLProtocol() {
        if urlProtocolEnabled {
            return
        }
        URLProtocol.registerClass(WebOfflineURLProtocol.self)
        URLProtocol.wk_registerScheme("http")
        URLProtocol.wk_registerScheme("https")
        urlProtocolEnabled = true
    }
    
    open class override func canonicalRequest(for request: URLRequest) -> URLRequest {
        return request
    }
    
    open class override func canInit(with request: URLRequest) -> Bool {
        guard let url = request.url else {
            return false
        }
        
        // 如果是我们要拦截的url
        if url.absoluteString.starts(with: WebConst.WEB_BASE_URL) {
            // 分析 url的path
            let pathComps = url.pathComponents
            if pathComps.count < 4 {
                return false
            }
            // 看看本地有没有离线文件
            let filePath = getOfflineFile(url: url)
            let fileExists = FileManager.default.fileExists(atPath: filePath)
            print("WebOffline intercept local=\(fileExists) \(url.absoluteString)")
            if fileExists {
                // 有就返回true, 这个请求就会被
                return true
            }
        }
        return false
    }
    
    public override func startLoading() {
        // 这里是拦截的代码
        guard let url = self.request.url else { return }
        let filePath = WebOfflineURLProtocol.getOfflineFile(url: url)
        if !FileManager.default.fileExists(atPath: filePath) {
            let error = NSError(domain: "WebOfflineURLProtocolError", code: NSURLErrorFileDoesNotExist, userInfo: nil)
            self.client?.urlProtocol(self, didFailWithError: error)
            return
        }
        do {
            // 返回本地数据
            let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
            let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)!
            self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
            self.client?.urlProtocol(self, didLoad: data)
            self.client?.urlProtocolDidFinishLoading(self)
        } catch {
            self.client?.urlProtocol(self, didFailWithError: error)
        }
    }
    
    
    private class func getOfflineFile(url: URL) -> String {
        let pathComps = url.pathComponents
        let project = pathComps[2]
        let version = pathComps[3]
        let filePath = pathComps.dropFirst(4).joined(separator: "/")
        return WebManager.shared.getOfflineFile(id: project, version: version, filePath: filePath)
    }
    
    public override func stopLoading() {
        
    }
}
